﻿using System;
using System.Runtime.InteropServices;
using System.Web.ModelBinding;
using System.Web.Mvc;
using demon;
using StudentInformationManagement.Models;

namespace StudentInformationManagement.Controllers
{
    public class StuInfoController : Controller
    {
        private ApplicationDbContext db = new ApplicationDbContext();

        public ActionResult Index()
        {
            return View(db.StuInfos.ToList());
        }

        [HttpPost]
        public ActionResult AddStudent(string stuid, string stuname, string stugender, string stuclass, string stutelephone, string stuemail, string stuQQ)
        {
            if (string.IsNullOrEmpty(stuid) || !Common.CheckStuId(stuid) ||
                string.IsNullOrEmpty(stuname) ||
                string.IsNullOrEmpty(stuclass) ||
                string.IsNullOrEmpty(stutelephone) ||
                string.IsNullOrEmpty(stuemail) ||
                string.IsNullOrEmpty(stuQQ) ||
                !Common.IsPhoneNum(stutelephone) ||
                !Common.IsEmail(stuemail) ||
                !Common.IsQQNum(stuQQ))
            {
                TempData["ErrorMessage"] = "输入信息不规范！";
            }
            else
            {
                string sqlStr = $"select count(*) from stuinfo where stuid='{stuid}'";
                if (Common.ExecuteNum(sqlStr) == 1)
                {
                    TempData["ErrorMessage"] = "该学生已存在！";
                }
                else
                {
                    string sqlStr2 = $"Insert into stuinfo(stuid,stuname,stugender,stuclass,stutelephone,stuemail,stuQQ) Values ('{stuid}','{stuname}','{stugender}','{stuclass}','{stutelephone}','{stuemail}','{stuQQ}')";
                    Common.ExecuteSql(sqlStr2);
                    TempData["SuccessMessage"] = "学生信息添加成功！";
                }
            }

            return RedirectToAction("Index");
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "StuId,StuName,StuGender,StuClass,StuTelephone,StuEmail,StuQQ")] StuInfo stuInfo)
        {
            if (ModelState.IsValid)
            {
                db.StuInfos.Add(stuInfo);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(stuInfo);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
